const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const { exec } = require('child_process')
const iconv = require('iconv-lite')

function createWindow () {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.cjs'),
      nodeIntegration: false,
      contextIsolation: true
    }
  })
  win.loadURL('http://localhost:5173') // 或你的本地打包地址
}

app.whenReady().then(createWindow)

const SAFE_COMMANDS = ['dir', 'ipconfig', 'echo', 'help', 'npm run build']
ipcMain.handle('run-cmd', async (event, command) => {
  const cmdName = command.split(' ')[0].toLowerCase()
  if (!SAFE_COMMANDS.includes(cmdName)) {
    return '不允许执行该命令'
  }
  return new Promise((resolve) => {
    exec(command, { encoding: 'buffer' }, (err, stdout, stderr) => {
      let output = ''
      if (stdout && stdout.length) output += iconv.decode(stdout, 'gbk')
      if (stderr && stderr.length) output += '\n' + iconv.decode(stderr, 'gbk')
      if (err && err.message) output += '\n' + err.message
      resolve(output)
    })
  })
}) 